import { defineStore } from "pinia";
import { loginApi, registerApi } from "../api/auth";
import { updateUserInfoApi, deleteUserByEmailApi } from "../api/user";
import { useStorage } from "@vueuse/core";
//验证登入逻辑 token持久化登入逻辑等
export const useUserStore = defineStore("user", () => {
  const token = useStorage("token", "");
  const login = (data) => {
    return new Promise((reslove, reject) => {
      loginApi(data)
        .then(({ code, msg, data }) => {
          if (code < 0) {
            reject(msg);
          } else {
            //loginApi成功就会走这个回调函数，其中 获取token 存储
            token.value = data;
            reslove("登入成功！");
          }
        })
        .catch((err) => {
          reject("系统繁忙");
        });
    });
  };

  const register = (data) => {
    return new Promise((reslove, reject) => {
      registerApi(data)
        .then(({ code, msg }) => {
          console.log(code, msg);
          //code 小于0时 出错
          if (code < 0) {
            reject(msg);
          } else {
            reslove("注册成功！");
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  const updateUserInfo = (userInfo) => {
    return new Promise((resolve, reject) => {
      updateUserInfoApi(userInfo)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  const deleteUserByEmail = (email) => {
    return new Promise((resolve, reject) => {
      deleteUserByEmailApi({ email })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  const clearToken = () => {
    token.value = "";
  };
  return {
    login,
    register,
    token,
    updateUserInfo,
    deleteUserByEmail,
    clearToken,
  };
});
